<template>
	<div class="course-manage-container" v-loading="loading">
		<!-- 主内容区 -->
		<div class="main-content">
			<!-- 左侧表单区域 -->
			<div class="form-container">
				<h2 class="section-title">课程信息编辑</h2>

				<!-- 课程标题 -->
				<el-form ref="formRef" :model="form" :rules="rules" label-position="top" label-width="120px">
					<el-form-item label="课程标题" prop="title" required>
						<el-input v-model="form.title" placeholder="请输入课程标题" maxlength="50" show-word-limit />
					</el-form-item>

					<!-- 图片管理模块 -->
					<!-- 课程主图 -->
					<el-form-item label="课程主图（封面）" prop="image">
						<el-upload class="avatar-uploader" action="#" :show-file-list="false" :auto-upload="false"
							:on-change="handleMainImageChange" :http-request="uploadMainImage">
							<img v-if="form.image" :src="form.image" class="avatar" />
							<el-icon v-else class="avatar-uploader-icon">
								<Plus />
							</el-icon>
						</el-upload>
					</el-form-item>
					<!-- 详情图模块 -->
					<el-form-item label="课程图片(只允许上传5张图片)" prop="courseImages" :required="false">
						<el-upload action="#" list-type="picture-card" :auto-upload="false" :on-preview="showPreview"
							:before-remove="handleRemoveImage" :limit="5" :http-request="customUpload"
							:on-change="handleFileChange" :file-list="form.courseImages.map(img => ({ url: img.imageUrl,
							 id: img.id
							 }))">
							<el-icon class="avatar-uploader-icon">
								<Plus />
							</el-icon>
						</el-upload>
						<div slot="tip" class="upload-footer">
							<el-button type="success" @click="submitUpload">
								上传至服务器
							</el-button>
						</div>
					</el-form-item>


					<!-- 课程描述 -->
					<el-form-item label="课程描述" prop="description">
						<el-input v-model="form.description" type="textarea" :rows="5" resize="vertical" />
					</el-form-item>

					<!-- 基础信息 -->
					<div class="basic-info-grid">
						<!-- 课程费用 -->
						<el-form-item label="课程费用" prop="fee">
							<el-input-number v-model="form.fee" :precision="2" :step="0.01" :min="0" />
						</el-form-item>

						<!-- 开课时间 -->
						<el-form-item label="开课时间" prop="startTime">
							<el-date-picker v-model="form.startTime" type="datetime" format="YYYY-MM-DD HH:mm:ss"
								value-format="YYYY-MM-DD HH:mm:ss" />
						</el-form-item>

						<!-- 课程状态 -->
						<el-form-item label="课程状态" prop="status">
							<el-select v-model="form.status" placeholder="请选择课程状态">
								<el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
									:value="item.value" />
							</el-select>
						</el-form-item>

						<!-- 报名人数限制 -->
						<el-form-item label="报名人数限制" prop="peopleLimit">
							<div class="people-limit">
								<el-input-number v-model="form.peopleLimit" :min="-1" :max="10000000"
									:disabled="isUnlimited" />
								<el-checkbox v-model="isUnlimited">不限人数</el-checkbox>
							</div>
						</el-form-item>
					</div>
				</el-form>
			</div>

			<!-- 右侧预览区域 -->
			<div class="preview-container">
				<h2 class="section-title">课程预览</h2>

				<!-- 封面图片 -->
				<div class="preview-image">
					<template v-if="form.image">
						<img :src="form.image" />
					</template>
					<template v-else-if="uploadedFiles.value && uploadedFiles.value.length > 0">
						<img :src="uploadedFiles.value[0]" />
					</template>
					<div v-else class="no-image">暂无封面图片</div>
				</div>

				<!-- 课程信息 -->
				<div class="preview-details">
					<h3>{{ form.title || "未设置课程标题" }}</h3>

					<ul>
						<li><el-icon name="date"></el-icon> {{ form.startTime || "未设置开课时间" }}</li>
						<li><el-icon name="money"></el-icon> {{ form.fee ? `¥${form.fee}` : "免费" }}</li>
						<li><el-icon name="user"></el-icon>
							{{isUnlimited || form.peopleLimit === -1 ? "人数不限" : `限${form.peopleLimit}人`}}</li>
						<li><el-icon name="flag"></el-icon> {{ getStatusText(form.status) }}</li>
					</ul>

					<div class="description">
						<h4>课程描述</h4>
						<p>{{ form.description || "暂无课程描述" }}</p>
					</div>
				</div>
			</div>
		</div>

		<!-- 底部操作栏 -->
		<div class="bottom-bar">
			<el-button @click="handleCancel">返回</el-button>
			<div class="right-buttons">
				<el-button @click="handleSaveDraft">保存草稿</el-button>
				<el-button type="primary" @click="handleSubmit">{{mode=='edit'?'修改课程':'发布课程'}}</el-button>
			</div>
		</div>

		<!-- 图片预览对话框 -->
		<el-dialog v-model="previewVisible" title="图片预览" width="1000px">
			<img :src="previewImage" class="preview-dialog-img" />
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="downloadImage(previewImage)">下载原图</el-button>
					<el-button type="primary" @click="previewVisible = false">关闭</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		name: 'CourseEditView',
	};
</script>

<script setup>
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		ref,
		computed,
		watch,
		onMounted,
		reactive
	} from "vue";
	import {
		Plus
	} from '@element-plus/icons-vue'
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";
	import {
		getCourseDetail,
		uploadCourseImage,
		insertCourses,
		updateCourses,
		deleteImage
	} from '@/api/course.js'
	/**
	 * 封装的定时器Promise
	 */
	const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
	const router = useRouter()
	const route = useRoute()
	const mode = route.params.mode // 'edit' 或 'add'
	const id = route.params.id // 编辑时有值，新增时为undefined
	const loading = ref(false)
	/**
	 * 用于显示已上传文件列表
	 */
	const uploadedFiles = ref([])
	/**
	 * 临时存储待上传文件
	 */
	const tempFiles = ref([])
	/**
	 * 表单数据
	 */
	const form = ref({
		title: "",
		description: "",
		image: "",
		fee: null,
		startTime: "",
		status: 0,
		peopleLimit: 0,
		courseImages: [],
	});
	/**
	 * 主图上传相关
	 */
	const mainImageFile = ref(null)
	/**
	 * 声明表单引用
	 */
	const formRef = ref(null)

	/**
	 * 状态选项
	 */
	const statusOptions = [{
			value: 0,
			label: "未开始"
		},
		{
			value: 1,
			label: "进行中"
		},
		{
			value: 2,
			label: "已结束"
		},
		{
			value: 3,
			label: "已取消"
		},
	];

	/**
	 * 是否不限人数
	 */
	const isUnlimited = computed({
		get: () => form.value.peopleLimit === -1,
		set: (value) => {
			if (value) {
				form.value.peopleLimit = -1
			} else {
				// 当取消不限人数时，可以设置一个默认值，比如100
				form.value.peopleLimit = 100
			}
		}
	})

	// 监听不限人数选项
	watch(isUnlimited, (val) => {
		form.value.peopleLimit = val ? -1 : 50
	})

	watch(
		() => form.value.courseImages,
		(newVal) => {
			console.log("图片数量:", newVal.length)
		}, {
			deep: true
		}
	)

	// 图片预览相关
	const previewVisible = ref(false);
	const previewImage = ref("");

	/**
	 * 表单校验规则
	 */
	const rules = reactive({
		title: [{
				required: true,
				message: '请输入课程标题',
				trigger: 'blur'
			},
			{
				max: 50,
				message: '课程标题不能超过50个字符',
				trigger: 'blur'
			}
		],
		courseImages: [{
			validator: (rule, value, callback) => {
				if (value && value.length > 5) {
					callback(new Error('最多上传5张图片'));
				} else {
					callback();
				}
			},
			trigger: ['change', 'blur']
		}],
		description: [{
			max: 500,
			message: '课程描述不能超过500个字符',
			trigger: 'blur'
		}],
		fee: [{
			type: 'number',
			min: 0,
			message: '课程费用不能为负数',
			trigger: 'blur'
		}],
		startTime: [{
			required: true,
			message: '请选择开课时间',
			trigger: 'change'
		}],
		status: [{
			required: true,
			message: '请选择课程状态',
			trigger: 'change'
		}],
		peopleLimit: [{
			validator: (rule, value, callback) => {
				if (!isUnlimited.value && (value === null || value === undefined || value < 0)) {
					callback(new Error('请输入有效的报名人数限制'));
				} else {
					callback();
				}
			},
			trigger: 'blur'
		}]
	});

	/**
	 * 处理主图文件变化
	 */
	const handleMainImageChange = (file) => {
		mainImageFile.value = file.raw
		// 本地预览
		const reader = new FileReader()
		reader.onload = (e) => {
			form.value.image = e.target.result
		}
		reader.readAsDataURL(file.raw)
	}

	/**
	 * 上传主图
	 */
	const uploadMainImage = async () => {
		if (!mainImageFile.value) return

		try {
			const formData = new FormData()
			formData.append('images', mainImageFile.value);
			const res = await uploadCourseImage(formData)
			if (res.code === 200 && res.data.length > 0) {
				form.value.image = res.data[0].imageUrl
				ElMessage.success('主图上传成功')
				return true
			} else {
				ElMessage.error(res.message || '主图上传失败')
				return false
			}
		} catch (error) {
			console.error('主图上传失败:', error)
			ElMessage.error('主图上传失败')
			return false
		}
	}

	/**
	 * 获取状态文本
	 */
	const getStatusText = (status) => {
		const option = statusOptions.find((item) => item.value === status);
		return option ? option.label : "未知状态";
	};

	/**
	 * 显示图片预览
	 */
	const showPreview = (file) => {
		previewImage.value = file.url;
		previewVisible.value = true;
	};

	/**
	 * 下载图片
	 */
	const downloadImage = (url) => {
		const link = document.createElement("a");
		link.href = url;
		link.download = `course-image-${new Date().getTime()}.jpg`;
		document.body.appendChild(link);
		link.click();
		document.body.removeChild(link);
	};

	/**
	 * 删除图片
	 */
	const handleRemoveImage = (file, fileList) => {
		return new Promise((resolve, reject) => {
			ElMessageBox.confirm("确定删除该图片吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				if (file.id) {
					// 已上传文件：调用 API 删除
					deleteImage(file.id)
						.then(() => {
							// 从 form.courseImages 中移除
							form.value.courseImages = form.value.courseImages.filter(img => img
								.id !== file.id);
							ElMessage.success("删除成功");
							resolve(true);
						})
						.catch((error) => {
							ElMessage.error("删除失败：" + error.message);
							reject(false);
						});
				} else {
					// 本地未上传文件：仅从 tempFiles 中移除
					tempFiles.value = tempFiles.value.filter(f => f.uid !== file.uid);
					ElMessage.success("删除成功");
					resolve(true);
				}
			}).catch(() => {
				reject(false); // 用户取消删除
			});
		});
	};

	/**
	 * 保存草稿
	 */
	const handleSaveDraft = () => {
		ElMessage.success("草稿保存成功");
	};

	/**
	 * 发布课程
	 */
	const handleSubmit = async () => {
		try {
			await formRef.value.validate();

			form.value.courseImages = uploadedFiles.value;

			if (uploadedFiles.value.length > 0 && !form.value.image) {
				form.value.image = uploadedFiles.value[0].imageUrl
			}

			const apiCall = mode === 'edit' ? updateCourses : insertCourses;
			const res = await apiCall(form.value);

			if (res.code === 204) {
				ElMessage.success(res.message);
				if (mode === 'edit') {
					await delay(500);
					await fetchCourseData();
				}
				return;
			}

			const errorMsg = res.errors || res.message;
			if (errorMsg) {
				ElMessage.error(errorMsg);
			}
		} catch (error) {
			console.error('提交失败:', error);
			ElMessage.error(`操作失败: ${error.message || '请检查表单数据'}`);
		}
	};


	/**
	 * 取消编辑
	 */
	const handleCancel = () => {
		ElMessageBox.confirm("确定放弃当前编辑的内容吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
			.then(() => {
				ElMessage.info("已取消编辑");
				router.back(-1)
			})
			.catch(() => {});
	};

	/**
	 * 存储没上传的图片
	 */
	const handleFileChange = (file, fileList) => {
		// 过滤出未上传的文件（status 为 'ready' 的文件）
		const pendingFiles = fileList.filter(item => item.status === 'ready');
		// 确保不超过限制
		tempFiles.value = pendingFiles.slice(-5);
		console.log("tempFiles.value", tempFiles.value);
	}

	/**
	 * 自定义图片上传方法
	 */
	const customUpload = async () => {
		try {
			// 调用API上传
			const files = tempFiles.value.map(item => item.raw || item); // 关键：确保拿到 File 对象

			if (files.length === 0) {
				console.error('没有有效的文件可上传');
				return;
			}

			const formData = new FormData();

			// 后端接收的是 List<MultipartFile>，字段名必须是 "images"
			files.forEach(file => {
				formData.append('images', file); // 关键点：字段名必须是 "images"
			});

			const response = await uploadCourseImage(formData);

			// 上传成功处理
			if (response.code === 200) {
				ElMessage.success('图片上传成功')
				const courseImages = form.value.courseImages.map(img => ({
					imageUrl: img.imageUrl
				}));
				courseImages.push(...response.data)
				uploadedFiles.value = courseImages
			} else {
				ElMessage.error(response.message || '图片上传失败')
				return Promise.reject(new Error('图片上传失败'))
			}
		} catch (error) {
			console.error('图片上传出错:', error)
			ElMessage.error('图片上传出错')
			return Promise.reject(error)
		}
	}

	/**
	 * 手动触发上传所有文件
	 */
	const submitUpload = async () => {
		try {

			// 如果有新上传的主图，先上传主图
			if (mainImageFile.value) {
				const uploadSuccess = await uploadMainImage()
				if (!uploadSuccess) return
			}

			customUpload()
			return true
		} catch (error) {
			console.error('批量上传失败', error)
			return false
		}
	}

	/**
	 * 获取课程详情
	 */
	const fetchCourseData = async () => {
		loading.value = true
		try {
			const res = await getCourseDetail(id)
			// 确保数据存在
			if (res.data) {
				form.value = res.data
			}
		} catch (error) {
			ElMessage.error('获取课程详情失败')
		} finally {
			loading.value = false
		}
	}

	onMounted(() => {
		// 编辑模式：加载数据
		if (mode === 'edit' && id) {
			fetchCourseData()
		}
		// 新增模式：保留空表单
	})
</script>

<style scoped>
	.course-manage-container {
		min-height: 100vh;
		background-color: #f9fafb;
		padding: 20px;
		/* 继承父容器高度 */
		height: 95%;
		min-height: 0;
		overflow-y: auto;
	}

	.breadcrumb-container {
		background-color: white;
		padding: 15px 20px;
		margin-bottom: 20px;
		box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
	}

	.section-title {
		font-size: 1.25rem;
		font-weight: 600;
		margin-bottom: 1.5rem;
	}

	.main-content {
		display: flex;
		gap: 20px;
		flex-wrap: wrap;
	}

	.form-container {
		flex: 2;
		min-width: 300px;
		background-color: white;
		padding: 20px;
		border-radius: 4px;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
	}

	.preview-container {
		flex: 1;
		min-width: 300px;
		background-color: white;
		padding: 20px;
		border-radius: 4px;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
		position: sticky;
		top: 20px;
	}

	.bottom-bar {
		margin-top: 20px;
		padding: 15px 20px;
		background-color: white;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.right-buttons {
		display: flex;
		gap: 10px;
	}

	.preview-image {
		width: 100%;
		height: 12rem;
		overflow: hidden;
		border-radius: 4px;
		margin-bottom: 1.5rem;
	}

	.preview-image img {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.no-image {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #f3f4f6;
		color: #9ca3af;
	}

	.preview-details h3 {
		font-size: 1.1rem;
		font-weight: 600;
		margin-bottom: 1rem;
	}

	.preview-details ul {
		list-style: none;
		padding: 0;
		margin-bottom: 1.5rem;
	}

	.preview-details li {
		margin-bottom: 0.75rem;
		color: #6b7280;
	}

	.preview-details h4 {
		font-size: 0.875rem;
		font-weight: 500;
		color: #4b5563;
		margin-bottom: 0.5rem;
	}

	.description p {
		color: #6b7280;
		font-size: 0.875rem;
		line-height: 1.5;
	}

	.basic-info-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 1.5rem;
	}

	.people-limit {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.preview-dialog-img {
		width: 100%;
		max-height: 500px;
		object-fit: contain;
	}

	.dialog-footer {
		text-align: right;
	}

	.upload-footer {
		margin-top: 10px;
		text-align: center;
	}

	.avatar-uploader {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
		width: 178px;
		height: 100px;
	}

	.avatar-uploader:hover {
		border-color: var(--el-color-primary);
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 100px;
		text-align: center;
		line-height: 100px;
	}

	.avatar {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.upload-tip {
		font-size: 12px;
		color: var(--el-text-color-secondary);
		margin-top: 8px;
	}
</style>